<?php

namespace Modules\H5\Http\Controllers\Search;

use Modules\Common\Models\Ebooks;
use Modules\Common\Models\SearchRecords;
use Modules\Common\Models\Keywords;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;

class Search
{
    /**
     * 搜索书籍并记录搜索历史
     * @Route(path="/api/h5/search-books")
     */
    public function searchBooks()
    {
        $keyword = request('keyword');
        $is_free = request('is_free');
        $query = Ebooks::where('book_name', 'like', '%' . $keyword . '%')->with(['category']);
        // 如果 $is_free 参数不为空，则添加该条件
        if (!empty($is_free)) {
            $query->where('is_free', $is_free);
        }
        
        // 检查关键词是否已存在
        $keywordEntry = Keywords::where('keyword', $keyword)->first();
        if ($keywordEntry) {
            // 更新关键词的搜索次数和最后搜索时间
            Keywords::where('id', $keywordEntry->id)->update([
                'search_count' => $keywordEntry->search_count + 1,
                'last_searched' => date('Y-m-d H:i:s')
            ]);
            $keywordId = $keywordEntry->id;
        } else {
            // 创建新的关键词
            $keywordModel = Keywords::create([
                'keyword' => $keyword,
                'search_count' => 1,
                'last_searched' => date('Y-m-d H:i:s'),
            ]);
            $keywordId = $keywordModel->id;
        }
        $sid = auth('web')->user()->sid;
        $eid = auth('web')->user()->eid;
        // 记录搜索历史
        SearchRecords::create([
            'user_id' => auth('web')->user()->id, // 获取用户 ID
            'keyword_id' => $keywordId,
            'search_time' => date('Y-m-d H:i:s'),
            'sid' => $sid,
            'eid' => $eid
        ]);
        $data = $query->where('is_published',1)->orderBy('created_at', 'desc')->paginate(request('per_page', 15));
        return Api::success($data);
    }

    /**
     * 获取用户的搜索历史
     * @Route(path=/api/h5/search-history)
     */
    public function getSearchHistory()
    {
        $userId = auth('web')->user()->id; //通过获取用户ID
        $searchHistory = SearchRecords::where('user_id', $userId)->with(['keyword'])->orderBy('created_at', 'desc')->paginate(request('per_page', 15));

        return Api::success($searchHistory);
    }
}